import axios from 'axios'


const service = axios.create({
    responseType: 'arraybuffer'
})

service.interceptors.request.use(config => {
    config.headers['Authorization'] = window.sessionStorage.getItem('tokenStr');
    return config;
}), error => {
    console.log(error);
};

service.interceptors.response.use(resp => {
    const headers = resp.headers;
    let reg = RegExp('/applicadtion\/json/');
    if (headers['Content-Type'].match(reg)) {
        resp.data = unitToString(resp.data);

    } else {
        let fileDownLoad = require('js-file-download');
        let fileName = headers['content-disposition'].split(';')[1].split('fileName=')[1];
        let contentType = headers['content-Type'];
        fileName = decodeURIComponent(fileName);
        fileDownLoad(resp.data, fileName, contentType);
    }
}), error => {
    console.log(error);
}


function unitToString(unitArray) {
    let encodeString = String.fromCharCode.apply(null, new Uint8Array(unitArray));
    decodedString = decodeURIComponent(escape(encodeString));
    return JSON.parse(decodedString);
}

let base = '';
export const downLoadRequest = (url, params){
    return service({
        method: 'get',
        url: `${base}${url}`,
        data: params
    })
}

export default service;